Dir["lib/tasks/*.rake"].each { |ext| load ext } if defined?(Rake)
require "railtie" if defined?(Rails)
module TemplateWrapper
#puts'Loading TemplateWrapper Module'
  @environment = :development
  @skip_templates = {}
  @rails_version = Rails.version
  @environment = :not_recommended unless Rails.env == 'development'
  mattr_accessor :image_src # "images/textmate.png"
  mattr_accessor :href # :regex, {:class => 'partial_mate_link'}
  mattr_accessor :wrapper_element # :span, {:class => 'partial_mate_span'}
  mattr_accessor :default_rendering # :full
  
  #ONLY in development!
  if @environment != :development
    puts "The template_wrapper gem should not be used outside of development"
    puts "   template_wrapper will not load"
  else
    require "template_wrapper/mixin.rb"
    require "template_wrapper/mixins/rails#{@rails_version.split('.')[0]}"
    self.image_src ||= "http://circuitllc.com/template_wrapper/images/ruby_next.png"
    self.href ||= {:link =>'txmt://open/?url=file://#{replace}&line=11&column=2', :class => 'template_wrapper_link'}
    self.wrapper_element ||= {:element => :span, :class => 'template_wrapper'}
    self.default_rendering = :full
  end

  def self.skip_wrap(template_path, type=:blank )
    @skip_templates.store(template_path.gsub("#{Rails.root}/", ''),type) 
  end

  def self.wrap(path,content)
    if @skip_templates.keys.include?(path)
       rendering = @skip_templates[path] || :blank
       html = encapsulate_template(path,content,rendering)
    else
      html = encapsulate_template(path,content)
    end
    @skip_templates = {}
    html
  end
  
  private
  def self.encapsulate_template(path,content,rendering=self.default_rendering)
    if path =~ /_mailer\// || rendering == :blank
      content
    else
      case rendering
      when :full
        html = <<EOHTML
    <a class='#{self.href[:class]}' href='txmt://open/?url=file://#{Rails.root}/#{path}&line=11&column=2'><img src='#{self.image_src}' alt='#{path}' title='#{path}' style='max-width:16px; max-height:16px;'/>#{path.gsub('app/views/','')}</a><#{self.wrapper_element[:element].to_s} class='#{self.wrapper_element[:class]}' id='#{path}'>#{content}</span>    
EOHTML
      when :icon
        html = <<EOHTML
    <a class='#{self.href[:class]}' href='txmt://open/?url=file://#{Rails.root}/#{path}&line=11&column=2'>
      <img src='#{self.image_src}' alt='#{path}' title='#{path}' style='max-width:16px; max-height:16px;'/>
    </a>
    <#{self.wrapper_element[:element].to_s} class='#{self.wrapper_element[:class]}' id='#{path}'>
      #{content}
    </#{self.wrapper_element[:element].to_s}>    
EOHTML
      when :comment
            html = <<EOHTML
    <!-- BEGIN: #{path} -->
    #{content}
    <!-- END: #{path} -->
EOHTML
      when :blank
        html = content 
      end
      CGI::unescapeHTML(html)
    end
  end

end
